package com.example.administrator.social.activitys;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.example.administrator.social.R;
import com.example.administrator.social.adapter.FriendAddRecordAdapter;
import com.example.administrator.social.adapter.SearchContactAdapter;
import com.example.administrator.social.model.Contact;
import com.example.administrator.social.util.AllenUtils;
import com.example.administrator.social.util.HttpUtils;
import com.example.administrator.social.util.request.CustomRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;

public class NewFriendsActivity extends AppCompatActivity implements TextView.OnEditorActionListener,
        View.OnClickListener,View.OnKeyListener,TextWatcher{
    private static final int SEARCH_CONTACT_UPDATE_IU = 0;
    private static final int UPDATE_ADAPTER = 1;
    private static final int NETWORK_ERROR = 2 ;
    private static final int HINT_PROGRESS_BAR = 4 ;
    private static final int SHOW_PROGRESS_BAR = 3 ;
    EditText mSearchEdit;
    ImageView mSearchDeleteImage;
    Toolbar mToolbar;
    TextView mGoBack,
            mSearchNoContact,//搜索未搜索到任何信息提示文本
            mNewFriendNoContact;//新朋友列表未搜索到任何信息提示文本
    Context mContext;
    LinearLayout mQcCodeScanLayout,
            mNewFriendLayout;//新朋友列表布局（添加申请，添加过的联系人）
    FrameLayout mFindFriendLayout;//搜到到的用户列表布局.
    RecyclerView mFindContactRecycler,//搜到到的用户列表
            mNewFriendRecycler;//新朋友列表
    ProgressBar mProgressBar;

    String mUserName;
    List<Contact> mSearchContactList = new ArrayList<>();
    //申请列表，用户信息
    List<Contact> mAddRequestList = new ArrayList<>();

    RequestQueue mRequestQueue;
    FriendAddRecordAdapter mRecordAdapter;
    SearchContactAdapter mSearchContactAdapter;


    //作为时间标志
    long flagTime = 0;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE_ADAPTER:
                    updateAdapter();break;
                case NETWORK_ERROR:
                    AllenUtils.showToast(mContext, getResources().getString(R.string.network_error));
                    isShowProgress(0);
                    break;
                case HINT_PROGRESS_BAR:
                    isShowProgress(0);break;
                case SHOW_PROGRESS_BAR:
                    isShowProgress(1);break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_friends);
        AllenUtils.setActionBarColor(getWindow(), this, R.color.toolbar_color);
        mContext = this;
        SharedPreferences preferences = mContext.getSharedPreferences("user", Context.MODE_PRIVATE);
        mUserName = preferences.getString("name", "");
        mToolbar = (Toolbar) findViewById(R.id.new_friend_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mRequestQueue =  Volley.newRequestQueue(mContext);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isShowProgress(1);
        //加载数据
        //获取申请添加好友的用户
        getAddFriendsRecord();

        //更新适配器
        //updateAdapter();

        EMClient.getInstance().chatManager().addMessageListener(listener);
        //进入当前页面，将所有未读信息记录，表示已读
        updateItemStatus();
    }

    private void updateAdapter() {
        mRecordAdapter.updateData(mAddRequestList);
        mRecordAdapter.notifyDataSetChanged();
        isShowProgress(0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(listener);
    }

    /**
     * 将所有申请信息状态修改为已读
     * one：申请者，two:被申请者
     * 查询 two中的所有申请者，修改状态
    */
    private void updateItemStatus() {
        String url = HttpUtils.HTTP_URL+"updateFriendRecordStatus";
        Map<String, String> map = new HashMap<>();
        map.put("user_name",mUserName);
        HttpUtils.postTextImageFile(mContext, url, map, null, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("updateItemStatus IOException"+e);
            }
            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                System.out.println("updateItemStatus response"+response);
            }
        });
    }

    private void initView() {
        //加载图标
        mProgressBar = (ProgressBar) findViewById(R.id.new_friend_progress);
        mSearchEdit = (EditText) findViewById(R.id.new_friend_search);
        mGoBack = (TextView) findViewById(R.id.new_friend_go_back);
        //二维码
        mQcCodeScanLayout = (LinearLayout) findViewById(R.id.new_friend_qc_code_scan);
        //已添加，或申请列表
        mNewFriendLayout = (LinearLayout) findViewById(R.id.new_friend_linear_layout);
        //搜索的用户信息列表
        mFindFriendLayout = (FrameLayout) findViewById(R.id.find_friend_frame_layout);
        //搜索界面未搜索到信息提示文本
        mSearchNoContact = (TextView) findViewById(R.id.search_friend_no_search_hint);
        //新朋友列表未搜索到任何信息提示文本
        mNewFriendNoContact = (TextView) findViewById(R.id.new_friend_no_search_hint);
        //添加申请、添加历史列表。
        mNewFriendRecycler = (RecyclerView) findViewById(R.id.new_friend_recycler);
        //查询到的好友列表
        mFindContactRecycler = (RecyclerView) findViewById(R.id.find_friend_recycler);
        //清空搜索框内容
        mSearchDeleteImage = (ImageView) findViewById(R.id.new_friend_search_delete_image);
        mSearchDeleteImage.setOnClickListener(this);

        initRecycler();
        initSearchRecycler();
        mSearchEdit.setOnEditorActionListener(this);
        mSearchEdit.addTextChangedListener(this);
        mSearchEdit.setOnKeyListener(this);
        mGoBack.setOnClickListener(this);
    }


    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (v.getId()==R.id.new_friend_search&&keyCode==KeyEvent.KEYCODE_BACK){
            mSearchEdit.setText("");
            mSearchEdit.clearFocus();
            mNewFriendLayout.setVisibility(View.VISIBLE);
            return true;
        }
        return false;
    }



    /**
     * 更新申请列表数据
     * 我是two，别人是one，和同意添加相反
     */
    private void getAddFriendsRecord() {
        String url = HttpUtils.HTTP_URL +"getAddFriendsRecord";
        //获取用户被添加记录、也就是其他用户的申请记录
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equals("102")){
                    Toast.makeText(mContext,R.string.no_search_data,Toast.LENGTH_SHORT).show();
                    mHandler.sendEmptyMessage(HINT_PROGRESS_BAR);
                    return;
                }
               mAddRequestList = new Gson().fromJson(response.trim(),new TypeToken<List<Contact>>(){}.getType());
               runOnUiThread(new Runnable() {
                   @Override
                   public void run() {
                       if(mAddRequestList==null||mAddRequestList.size()==0){
                           mNewFriendNoContact.setVisibility(View.VISIBLE);
                           mNewFriendRecycler.setVisibility(View.GONE);
                           return;
                       }else{
                           mNewFriendNoContact.setVisibility(View.GONE);
                           mNewFriendRecycler.setVisibility(View.VISIBLE);
                       }
                     mHandler.sendEmptyMessage(UPDATE_ADAPTER);
                   }
               });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("getAddFriendsRecord volleyError = " + volleyError);
              //  mNewFriendNoContact.setVisibility(View.VISIBLE);
              //  mNewFriendRecycler.setVisibility(View.GONE);
                mHandler.sendEmptyMessage(NETWORK_ERROR);
            }
        });
        Map<String, String> map = new HashMap<>();
        map.put("name", AllenUtils.getUserName(mContext));
        request.setParamsMap(map);
        mRequestQueue.add(request);
    }

    private void initRecycler() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        mNewFriendRecycler.setLayoutManager(manager);

        mRecordAdapter = new FriendAddRecordAdapter(mContext,mAddRequestList);
        mNewFriendRecycler.setAdapter(mRecordAdapter);
        mRecordAdapter.setCallBack(new FriendAddRecordAdapter.RecordCallBack() {
            @Override
            public void agreesButtonOnClick(View view, int position) {
                if (AllenUtils.isFrequentClick(mContext, view.getId(), System.currentTimeMillis()))
                    return;
                Contact info = mAddRequestList.get(position);
                sendRequestAddContact(info, position);
            }

            @Override
            public void itemOnClick(View view, int position) {
                Intent intent = new Intent(mContext, UserInfoActivity.class);
                intent.putExtra("contact", mAddRequestList.get(position));
                startActivity(intent);
            }
        });
    }



    /**
     * 发送请求同意用户添加申请
     * 被添加：(主动添加，申请)user_one，user_two(被申请)
     * user_one加---》》user_two
     * @param
     */
    private void sendRequestAddContact(final Contact info, final int position) {
        String url = HttpUtils.HTTP_URL+"addOneFriend";
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equals("100")){
                    //获取最新的好友列表，和申请列表数据
                    //获取申请添加好友的用户
                    getAddFriendsRecord();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mHandler.sendEmptyMessage(NETWORK_ERROR);
            }
        });
        Map<String, String> map = new HashMap<>();
        map.put("user_one",info.getName());
        map.put("user_two",mUserName);
        request.setParamsMap(map);
        mRequestQueue.add(request);
    }

    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        if (view.getId() == R.id.new_friend_search) {
            if(mSearchEdit.length()==0||mSearchEdit.getText().toString().trim().equals("")){
                return true;
            }
            updateUI();
            //sendHttpRequest search
            doHttpSearchContact(view.getText().toString());
        }
        return true;
    }

    private void updateUI() {
        mNewFriendLayout .setVisibility(View.GONE);
        mFindFriendLayout.setVisibility(View.VISIBLE);
    }


    /**
     * 根据：用户名，昵称，手机号搜索联系人
     * @param value 用户名、昵称、手机号搜索联系人
     */
    private void doHttpSearchContact(String value) {
        String url = HttpUtils.HTTP_URL + "searchContact";
        CustomRequest request = new CustomRequest(url, Request.Method.POST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println("doHttpSearchContact response = " + response);
                if (response.trim().equals("")||response.trim().equals("101")){
                    mSearchNoContact.setVisibility(View.VISIBLE);
                    mFindContactRecycler.setVisibility(View.GONE);
                    return;
                }
                mSearchContactList = new Gson().fromJson(response.trim(),new TypeToken<List<Contact>>(){}.getType());
                mSearchContactAdapter.updateDataList(mSearchContactList);
                mSearchContactAdapter.notifyDataSetChanged();
                mFindContactRecycler.setVisibility(View.VISIBLE);
                mSearchNoContact.setVisibility(View.GONE);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mHandler.sendEmptyMessage(NETWORK_ERROR);
                mFindContactRecycler.setVisibility(View.GONE);
                mSearchNoContact.setVisibility(View.VISIBLE);
            }
        });
        Map<String, String> map = new HashMap<>();
        map.put("value", value);
        map.put("user", mUserName);
        request.setParamsMap(map);
        mRequestQueue.add(request);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.new_friend_go_back:
                finish();
                break;
            case R.id.new_friend_search_delete_image:
                mSearchEdit.setText("");
                mNewFriendLayout .setVisibility(View.VISIBLE);
                mFindFriendLayout.setVisibility(View.GONE);
                break;

        }
    }


    public void initSearchRecycler() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        mFindContactRecycler.setLayoutManager(manager);
        mSearchContactAdapter =  new SearchContactAdapter(mContext,mSearchContactList);
        mSearchContactAdapter.setSearchContactCallback(new SearchContactAdapter.SearchContactCallback() {
            @Override
            public void itemOnClick(View view, int position) {
                Intent intent = new Intent(mContext,UserInfoActivity.class);
                intent.putExtra("contact",mSearchContactList.get(position));
                startActivity(intent);
            }

            @Override
            public void agreeButtonOnClick(final View view, int position) {
               if(AllenUtils.isFrequentClick(mContext,view.getId(),System.currentTimeMillis())) return;
                final Contact contact = mSearchContactList.get(position);
                //向服务器添加申请记录
                addFriendRequestRecord(contact);
                //发送透传消息，添加好友申请
                HttpUtils.sendAddRequestCmdMessage(contact);

            }
        });
        mFindContactRecycler.setAdapter(mSearchContactAdapter);
    }


    /**
     * 请求发送成功后，向服务器添加请求记录
     * 发送请求时 user_one添加我方 user_two被添加方，反之。。。。
     * @param
     */
    private void addFriendRequestRecord(Contact contact) {
        String url = HttpUtils.HTTP_URL+"addFriendRequestRecord";
        String date = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(new Date(System.currentTimeMillis()));
        Map<String, String> map = new HashMap<>();
        map.put("name_one",mUserName);
        map.put("name_two",contact.getName());
        map.put("date",date);
        map.put("phone",contact.getPhone());
        HttpUtils.postTextImageFile(mContext, url, map, null, new Callback() {
             @Override
             public void onFailure(Call call, IOException e) {
                 mHandler.sendEmptyMessage(NETWORK_ERROR);
             }

             @Override
             public void onResponse(Call call, okhttp3.Response response) throws IOException {
                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         Toast.makeText(mContext,R.string.message_send_success,Toast.LENGTH_SHORT).show();
                     }
                 });
             }
        });
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }
    @Override
    public void afterTextChanged(Editable s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mSearchDeleteImage.setVisibility(mSearchEdit.length()>0?View.VISIBLE:View.GONE);
                mNewFriendLayout.setVisibility(mSearchEdit.length()>0?View.GONE:View.VISIBLE);
                mFindFriendLayout.setVisibility(mSearchEdit.length()>0?View.VISIBLE:View.GONE);
            }
        });
    }




    private EMMessageListener listener = new EMMessageListener() {

        /**
         * 以下方法监听消息
         * @param
         */
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息.
            //更新申请列表
            getAddFriendsRecord();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }
        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };
    private void isShowProgress(int value){
        mProgressBar.setVisibility(value==1?View.VISIBLE:View.GONE);
    }

}
